//
//  XJCMusicViewController.m
//  On The Load
//
//  Created by 许嘉成 on 15/11/5.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "XJCMusicViewController.h"

#import "AppTools.h"
#import "XJCMusciModel.h"
#import "MusicTableViewCell.h"
#import "SDCycleScrollView.h"
#import "MJRefresh.h"
#import "MusicDetailViewController.h"
#import "MJRefresh.h"
#import "UIScrollView+PullToRefreshCoreText.h"
#import "STKAudioPlayer.h"
#import "STKDataSource.h"
#import <MJRefresh.h>

@interface XJCMusicViewController ()<SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>


@property(nonatomic,retain)UITableView *musicTV;//音乐tableview
@property(nonatomic,retain)NSMutableArray *musicArray;//音乐数组
@property(nonatomic,assign)NSInteger page;//记录页码
@property(nonatomic,assign)BOOL isUpLoading;//记录上拉还是下拉
@property(nonatomic,retain)UIButton *rightBtn;//导航栏右侧按钮

@end

@implementation XJCMusicViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.rightBtn.hidden = NO;
    if ([[[MusicDetailViewController sharePlayerViewController] player] state] == STKAudioPlayerStatePlaying) {
        //通过改变view的transform属性值中的z轴坐标来实现旋转
        CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        basicAnimation.duration = 5;
        //开始动画的起始位置
        basicAnimation.fromValue = [NSNumber numberWithInt:0];
        //M_PI是180度
        basicAnimation.toValue = [NSNumber numberWithInt:M_2_PI*2];
        //动画重复次数,无限次
        [basicAnimation setRepeatCount:NSIntegerMax];
        //播放完毕之后是否逆向回到原来位置
        [basicAnimation setAutoreverses:NO];
        //是否叠加(追加)动画效果
        [basicAnimation setCumulative:YES];
        [self.rightBtn.layer addAnimation:basicAnimation forKey:@"basicAnimation"];
        //  开始旋转
        //  得到view当前动画时间偏移量
        CFTimeInterval stopTime = [self.rightBtn.layer timeOffset];
        //  初始化开始时间
        self.rightBtn.layer.beginTime = 0;
        //  初始化时间偏移量
        self.rightBtn.layer.timeOffset = 0;
        //  设置动画速度
        self.rightBtn.layer.speed = 1.0;
        //  计算时间差
        CFTimeInterval tempTime = [self.rightBtn.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        //  重新设置动画开始时间
        self.rightBtn.layer.beginTime = tempTime;
        
    }
    else{
        //  获得点击图片时的动画时间,为了下次开始动画用
        CFTimeInterval stopTime = [self.rightBtn.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        //  停止动画,速度设置为0
        self.rightBtn.layer.speed = 0;
        //  设置时间偏移量
        self.rightBtn.layer.timeOffset = stopTime;
        
    }
    self.navigationController.navigationBar.translucent = YES;
    [super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.musicArray = [NSMutableArray array];
    
    [self createMusicView];
    [self getAfnData];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createMusicView];

    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getAfnData)];
    _musicTV.footer = footer;
    self.page = 1;
}

//    //add pull to refresh
//    [self.musicTV addPullToRefreshWithPullText:@"Pull To Refresh" pullTextColor:[UIColor colorWithRed:0.293 green:1.000 blue:0.758 alpha:1.000] pullTextFont:DefaultTextFont refreshingText:@"Welcome echo" refreshingTextColor:[UIColor colorWithRed:0.033 green:0.720 blue:1.000 alpha:1.000] refreshingTextFont:DefaultTextFont action:^{
//        //下拉
//        [self drop];
//    }];
    
    
    //调用请求数据
//    self.page = 1;
//    [self drop];
//        [self getAfnData:self.page];
//    上拉
//    [self addFooter];
//}
//#pragma mark--下拉刷新协议方法(pull)
//- (void)drop
//{
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
//    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        __block XJCMusicViewController *vc = self;
//        vc.page = 1;
//        vc.isUpLoading = NO;
//        [vc getAfnData:vc.page];
//        [self.musicTV finishLoading];
//    });
//}

//请求数据
-(void)getAfnData
{
    [AppTools getAFN:[NSString stringWithFormat:@"http://echosystem.kibey.com/sound/hot?page=%ld", _page] andpara:nil andBlock:^(id result) {
        
        //解析数据
        NSMutableDictionary *bigDic = result;
        NSMutableDictionary *resultDic = [bigDic objectForKey:@"result"];
        NSMutableArray *dataArray = [resultDic objectForKey:@"data"];
        for (NSMutableDictionary *dic in dataArray) {
            XJCMusciModel *musicM = [[XJCMusciModel alloc]init];
            [musicM setValuesForKeysWithDictionary:dic];
            [self.musicArray addObject:musicM];
            NSLog(@"!_%@",musicM.id);
            
        }
        _page++;
        //刷新数据
        [self.musicTV reloadData];
        [self.musicTV.footer endRefreshing];
    } andfailBlock:^(id result) {
        
        
    }];
}
#pragma mark--创建table
//音乐模块儿视图
-(void)createMusicView
{
    self.navigationController.navigationBar.translucent = YES;
    self.musicTV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64)];
    self.musicTV.delegate = self;
    self.musicTV.dataSource = self;
    [self.view addSubview:self.musicTV];
    
    //头部视图
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 240*SCALEH)];
    headerView.backgroundColor = [UIColor whiteColor];
    self.musicTV.tableHeaderView = headerView;
    //轮播图
    NSArray *images = @[[UIImage imageNamed:@"IMG_1431.jpg"],
                        [UIImage imageNamed:@"IMG_1432.jpg"],
                        [UIImage imageNamed:@"IMG_1440.jpg"],
                        [UIImage imageNamed:@"IMG_1438.jpg"],
                        [UIImage imageNamed:@"IMG_1439.jpg"]
                        ];
    
    // 图片配文字
    NSArray *titles = @[@"聆听自己内心的声音",
                        @"环境压力下，音乐是浮木",
                        @"音乐是旅途上最好的充电器",
                        @"音乐是人类的第二语言",
                        @"一个人的音乐是心灵最深处地呻吟"
                        ];
    
    
    
    // 本地加载 --- 创建不带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, 200*SCALEH) imagesGroup:images];
    
    cycleScrollView.infiniteLoop = YES;
    cycleScrollView.delegate = self;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    [headerView addSubview:cycleScrollView];
    //         --- 轮播时间间隔，默认1.0秒，可自定义
    //cycleScrollView.autoScrollTimeInterval = 4.0;
    cycleScrollView.dotColor = [UIColor colorWithRed:0.545 green:0.902 blue:0.779 alpha:1.000]; // 自定义分页控件小圆标颜色
    cycleScrollView.titlesGroup = titles;
    [headerView addSubview:cycleScrollView];
    
    //右侧按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-yutoubaoicon-2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnAction)];
   
    
    //每日推荐
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100 * WIDTH/375,cycleScrollView.frame.size.height + 5 * HEIGHT/667, 175 * WIDTH/378, 30 * HEIGHT/667)];
    titleLabel.backgroundColor = [UIColor colorWithRed:0.545 green:0.902 blue:0.779 alpha:1.000];
    titleLabel.layer.masksToBounds = YES;
    titleLabel.layer.cornerRadius = 15 * WIDTH/375;
    titleLabel.text = @"每 日 推 荐";
    titleLabel.font = [UIFont systemFontOfSize:17 * SCALEH];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    //    titleLabel.userInteractionEnabled = YES;
    //    UITapGestureRecognizer *alistTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelAction)];
    //    [titleLabel addGestureRecognizer:alistTap];
    [headerView addSubview:titleLabel];
}

//右侧按钮事件
-(void)rightBtnAction
{
    
    MusicDetailViewController *musicDVC = [[MusicDetailViewController alloc]init];
    [musicDVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self presentViewController:[MusicDetailViewController sharePlayerViewController] animated:YES completion:^{
    }];
    
    
    
}

#pragma mark-- table协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.musicArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.musicTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    XJCMusciModel *musicM = [self.musicArray objectAtIndex:indexPath.row];
    static NSString *cellIdentifier = @"cell";
    MusicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MusicTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.musicM = musicM;
    return cell;
}
//cell点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailViewController *musicDVC = [MusicDetailViewController sharePlayerViewController];
    [musicDVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    XJCMusciModel *musicM = [self.musicArray objectAtIndex:indexPath.row];
    //传ID
    musicDVC.detailId = musicM.id;
    //传model
    musicDVC.musicM = musicM;
    [self presentViewController:musicDVC animated:YES completion:nil];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170*SCALEH;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
